package com.yantong.service.impl;

import com.yantong.constant.*;
import com.yantong.exception.BDException;
import com.yantong.mapper.*;
import com.yantong.pojo.*;
import com.yantong.pojo.vo.CentreAmountVo;
import com.yantong.pojo.vo.CentreCategoryVo;
import com.yantong.pojo.vo.CentreVo;
import com.yantong.service.*;
import com.yantong.utils.*;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * 商户  服务
 *
 * @author kanghaixin
 * @date 2018/8/24.16:30
 */
@Service
public class CentreServiceImpl implements CentreService {
	private static final Logger logger = LoggerFactory.getLogger(CentreServiceImpl.class);
	@Autowired
	private CentreMapper centreMapper;
	@Autowired
	private CentreRateMapper centreRateMapper;
	@Autowired
	private CentreAmountMapper centreAmountMapper;
	@Autowired
	private AmountLogMapper amountLogMapper;
	@Autowired
	private ProductCentreMapper productCentreMapper;
	@Autowired
	private CommissionService commissionService;
	@Autowired
	private MemberMapper memberMapper;
	@Autowired
    @Lazy
	private MemberService memberService;
	@Autowired
	private CentreCategoryService centreCategoryService;

	@Autowired
	private SalesmanMapper salesmanMapper;
	@Autowired
	private UserService userService;
	@Autowired
	@Lazy
	private OrderService orderService;
	@Autowired
	private StoreMapper storeMapper;
	@Autowired
	private CentreIndustryMapper centreIndustryMapper;

	private static final String RATE_CACHE_NAME = "centre_rate";

	@Value("${Applet.TemplatemsgCreateUserUrl}")
	private String templatemsgCreateUserUrl;

	@Override
	public PageUtils<Centre> listCentres(SysUser user, String name, String type, String status, int offset, int limit) {
		PageUtils<Centre> pageUtils = new PageUtils<>();

		CentreExample centreExample = new CentreExample();
		CentreExample.Criteria criteria = centreExample.createCriteria();
		Map<String, Object> map = new HashMap<>();
		if (StringUtils.isNotEmpty(name)) {
			criteria.andNameLike('%' + name + '%');
			map.put("name", name);
		}

		if (StringUtils.isNotEmpty(type)) {
			criteria.andTypeEqualTo(type);
			map.put("type", type);
		}
		if (StringUtils.isNotEmpty(status)) {
			criteria.andStatusEqualTo(status);
			map.put("status", status);
		}
		//如果是分公司或者代理，则只显示自己旗下得商户
		if (user.getFlag().equals(PermisFlag.BranchOffice)
				|| user.getFlag().equals(PermisFlag.AgentLevel1)
				|| user.getFlag().equals(PermisFlag.AgentLevel2)
				|| user.getFlag().equals(PermisFlag.AgentLevel3)
				|| user.getFlag().equals(PermisFlag.Salesman)) {
			map.put("loginUserId", user.getUserId());
			{
				logger.info("list centres not found by: name:{}, type:{}, status:{}", name, type, status);
				pageUtils.setRows(new ArrayList<>());
			}
		} else {
			int total = centreMapper.countByExample(centreExample);
			if (total > 0) {
				logger.info("list centres, name:{}, type:{}, status:{},total size:{}", name, type, status, total);
				pageUtils.setTotal(total);
				centreExample.setOrderByClause("create_time desc");
				pageUtils.setRows(centreMapper.selectByExample(centreExample, new RowBounds(offset, limit)));
			} else {
				logger.info("list centres not found by: name:{}, type:{}, status:{}", name, type, status);
				pageUtils.setRows(new ArrayList<>());
			}
		}
		return pageUtils;
	}

	@Override
	public List<Centre> listAllCentres() {
		CentreExample centreExample = new CentreExample();
		centreExample.or().andStatusEqualTo("1");
		return centreMapper.selectByExample(centreExample);
	}

	@Override
	public Boolean checkName(String name) {
		if (StringUtils.isEmpty(name)) {
			return true;
		}
		CentreExample centreExample = new CentreExample();
		centreExample.or().andNameEqualTo(name);
		int total = centreMapper.countByExample(centreExample);
		if (total > 0) {
			return false;
		}
		return true;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public int save(Centre centre) {
		if (centre == null) {
			return 0;
		}
		centreMapper.insertSelective(centre);
		CentreRate rate = new CentreRate();
		rate.setCentreId(centre.getCentreId());
		rate.setTradeRate(new BigDecimal(0.006));
		rate.setCashRate(new BigDecimal(0.006));

		CentreAmount ca = new CentreAmount();
		ca.setCentreId(centre.getCentreId());
		ca.setAmount(BigDecimal.valueOf(0));
		ca.setFrozenAmount(BigDecimal.valueOf(0));
		if (centre.getMid() != null) {
			ca.setMid(centre.getMid());
			centreAmountMapper.save(ca);
		} else {
			centreAmountMapper.addAmount(ca);
		}
		return centreRateMapper.saveCentreRate(rate);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public int saveCentre(CentreVo centre) {
		if (centre == null) {
			return 0;
		}

		List<Centre> list = centreMapper.selectByAccountMobile(centre.getAccountMobile());
		if (CollectionUtils.isNotEmpty(list)) {
			throw new BDException(centre.getAccountMobile() + "已被使用");
		}

        /*Centre c = centreMapper.selectByMid(centre.getMid());
        if (c != null) {
            return 0;
        }*/
		centreMapper.insertSelective2(centre);
		CentreRate rate = new CentreRate();
		rate.setCentreId(centre.getCentreId());
		rate.setTradeRate(new BigDecimal(0.006));
		rate.setCashRate(new BigDecimal(0.006));

		CentreAmountVo ca = new CentreAmountVo();
		ca.setCentreId(centre.getCentreId());
		ca.setAmount(BigDecimal.valueOf(0));
		ca.setFrozenAmount(BigDecimal.valueOf(0));
		if (centre.getMid() != null) {
			ca.setMid(centre.getMid());
		}
		centreAmountMapper.save(ca);
		return centreRateMapper.saveCentreRate(rate);
	}

	/**
	 * 商户详情 根据用户id
	 *
	 * @param centreId
	 * @return
	 */
	@Override
	public Centre getBymid(Long mid) {
		if (mid == null) {
			return null;
		}
		Centre centre = centreMapper.selectByMid(mid);
		if (centre != null) {
			centre.setCentreAmount(centreAmountMapper.getByKey(centre.getCentreId()));
		}
		return centre;
	}

	@Override
	public Centre getByKey(Long centreId) {
		if (centreId == null) {
			return null;
		}
		Centre centre = centreMapper.selectByPrimaryKey(centreId);
		if (centre != null) {
			centre.setCentreAmount(centreAmountMapper.getByKey(centreId));
			if (null != centre.getPcate() && centre.getPcate() != 0) {
				List<CentreCategoryVo> ccategoryList = centreCategoryService.listCategorys(centre.getPcate());
				centre.setCcategoryList(ccategoryList);
			}
		}
		return centre;
	}

	@Override
	public Centre getCentreById(Long centreId) {
		return centreMapper.selectByPrimaryKey(centreId);
	}


	@Override
	@Transactional(rollbackFor = Exception.class)
	public int updateCentre(Centre centre) {
		if (centre == null || centre.getCentreId() == null) {
			return 0;
		}

		Centre c = centreMapper.selectByPrimaryKey(centre.getCentreId());

		if (centre.getMid() != null && !centre.getMid().equals(c.getMid())) {
			//更换商户绑定人
			Member oldMember = memberMapper.selectByPrimaryKey(c.getMid());
			if (oldMember != null) {
				Member member = new Member();
				member.setId(c.getMid());
				member.setIsCentre(0);
				member.setIsteam(MemberType.NORMAL.getCode());
				//更新用户站点标识
				memberMapper.updateByPrimaryKeySelective(member);
			}

			Member newMember = new Member();
			newMember.setId(centre.getMid());
			newMember.setIsCentre(1);
			newMember.setCentreId(c.getCentreId());
			newMember.setIsteam(MemberType.COMMANDER.getCode());
			newMember.setCheckTime(new Date());

			newMember.setUpshopName(centre.getName());
			newMember.settProvince(centre.getProvince());
			newMember.settCity(centre.getCity());
			newMember.settArea(centre.getArea());
			newMember.settXiaoqu(centre.getName() + "门店");
			String coordinate = "";
			if (c.getLon() != null) {
				coordinate = coordinate.concat(c.getLon() + "").concat(",");
				newMember.setLng(c.getLon().toString());
			}
			if (c.getLat() != null) {
				coordinate = coordinate.concat(c.getLat() + "");
				newMember.setLat(c.getLat().toString());
			}
			newMember.settZuobiao(coordinate);
			//更新用户站点标识
			memberMapper.updateByPrimaryKeySelective(newMember);
		}

		return centreMapper.updateByPrimaryKeySelective(centre);
	}

	@Override
	public int removeCentre(Long centreId) {
		if (centreId == null) {
			return 0;
		}
		Centre centre = new Centre();
		centre.setCentreId(centreId);
		centre.setStatus("0");
		return centreMapper.updateByPrimaryKeySelective(centre);
	}

	@Override
	public int resumeCentre(Long centreId) {
		if (centreId == null) {
			return 0;
		}
		Centre centre = new Centre();
		centre.setCentreId(centreId);
		centre.setStatus("1");
		return centreMapper.updateByPrimaryKeySelective(centre);
	}

	@Override
	public int batchRemove(List<Long> centreIds) {
		if (CollectionUtils.isEmpty(centreIds)) {
			return 0;
		}
		return centreMapper.batchRemove(centreIds);
	}

	@Override
	public int batchHiden(List<Long> centreIds, Integer hide) {
		if (hide == 0) {
			//不隐藏
			return centreMapper.updCentreNotHide(centreIds);
		} else {
			//隐藏
			return centreMapper.updCentreHide(centreIds);
		}
	}



	@Override
	@Cacheable(value = RATE_CACHE_NAME, keyGenerator = "localKeyGenerator")
	public CentreRate getRateByCentreId(Long centreId) {
		if (centreId == null) {
			return null;
		}
		return centreRateMapper.getByCentreId(centreId);
	}

	@Override
	public CentreAmount getAmountByCentreId(Long centreId) {
		if (centreId == null) {
			return null;
		}
		return centreAmountMapper.getByKey(centreId);
	}

	@Override
	public int changeAmount(CentreAmount centreAmount) {
		if (centreAmount == null || centreAmount.getCentreId() == null) {
			return 0;
		}
		return centreAmountMapper.changeAmount(centreAmount);
	}


	/**
	 * 账户流水记录列表
	 *
	 * @param centreId
	 * @param start
	 * @param end
	 * @param orderSn
	 * @param offset
	 * @param limit
	 * @return
	 */
	@Override
	public List<AmountLog> getListAmountLogs(Long centreId, Date start, Date end, String orderSn, Integer flowType, int offset, int limit) {
		Map<String, Object> params = new HashMap<>(4);
		if (centreId != null) {
			params.put("centreId", centreId);
		}
		if (start != null) {
			params.put("start", start);
		}
		if (end != null) {
			params.put("end", end);
		}
		if (StringUtils.isNotEmpty(orderSn)) {
			params.put("orderSn", orderSn);
		}
		if (flowType != null) {
			params.put("flowType", flowType);
		}
		return amountLogMapper.listAmountLogs(params, new RowBounds(offset, limit));
	}

	@Override
	public int saveAmountLog(AmountLog amountLog) {
		if (amountLog == null) {
			return 0;
		}
		return amountLogMapper.saveAmountLog(amountLog);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public int saveAmountLog(Long orderId, Long centreId, OrderProduct op, String orderSn) {


		if (centreId == null) {
			return 0;
		}
		AmountLog al = new AmountLog();
		al.setOrderId(orderId);
		al.setCentreId(centreId);
		al.setOrderProductId(op.getId());
		al.setOrderSn(orderSn);
		al.setProductId(op.getProductId());
		al.setRemark("订单收货平台结算给站点余额,订单号：" + orderSn.concat(",").concat(String.valueOf(op.getId())).concat(op.getProductName()).concat(",销售价:").concat(op.getPrice().toString()).concat(",成本价:").concat(op.getCostprice().multiply(new BigDecimal(op.getTotal())).toString()));
		ProductCentre pc = productCentreMapper.getByKey(op.getProductId());
		if (pc == null) {
			return 0;
		}

		CentreRate cr = this.getRateByCentreId(centreId);
		if (cr != null) {
			if (cr.getTradeRate() != null) {
				BigDecimal fee = op.getPrice().multiply(cr.getTradeRate()).divide(BigDecimal.valueOf(1000), 4, BigDecimal.ROUND_HALF_UP);
				if (fee != null) {
					al.setPoundage(fee.setScale(2, BigDecimal.ROUND_UP));
				}
			}
			//商户商品提点百分比
			if (cr.getProfitRate() != null) {
				BigDecimal profitRate = op.getPrice().multiply(cr.getProfitRate()).divide(BigDecimal.valueOf(100), 4, BigDecimal.ROUND_HALF_UP);
				if (profitRate != null && pc.getProductId() == null) {
					//商户商品提点金额
					al.setProfitRate(profitRate.setScale(2, BigDecimal.ROUND_UP));
					//站点提点汇率
					al.setProfitMoney(cr.getProfitRate());
				}
			}
		}

		BigDecimal money = null;
		//商户商品
		if (pc.getProductId() == null || pc.getProductId() == 0) {
			al.setProductType(0);
			money = (op.getMarketprice()).multiply(BigDecimal.valueOf(op.getTotal())).subtract(al.getPoundage());
			if (al.getProfitRate() != null) {
				//减去站点提点价格
				money = money.subtract(al.getProfitRate());
			}
		} else {
			money = (op.getMarketprice().subtract(op.getCostprice())).multiply(BigDecimal.valueOf(op.getTotal())).subtract(al.getPoundage());
		}

		al.setRate(cr.getTradeRate());
		al.setFlowType(1);//站点毛利结算
		al.setMoney(money);
		CentreAmount centreAmount = centreAmountMapper.getByKey(centreId);
		al.setBeforeamount(centreAmount.getAmount());
		al.setAfteramount(centreAmount.getAmount().add(money));
		centreAmountMapper.changeAmount(new CentreAmount(centreId, money));
		/**自动发放佣金**/
		commissionService.autoGrant(op.getId());
		return amountLogMapper.saveAmountLog(al);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public int deductAmount(Long centreId, BigDecimal money, String orderSn, Long orderProductId, Integer flowType, String remark) {
		if (centreId == null || money == null) {
			return 0;
		}

		AmountLog al = new AmountLog();
		al.setCentreId(centreId);
		al.setOrderProductId(orderProductId);
		al.setOrderSn(orderSn);
		al.setMoney(BigDecimal.ZERO.subtract(money));
		if (StringUtils.isNotEmpty(orderSn)) {
			al.setRemark(remark + orderSn);
			if (orderProductId != null) {
				al.setRemark(al.getRemark().concat(",").concat(String.valueOf(orderProductId)));
			}
		}
		al.setFlowType(flowType);

		return amountLogMapper.saveAmountLog(al);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public int supplyDeductAmount(Long centreId, BigDecimal money, String orderSn, Long orderProductId) {
		if (centreId == null || money == null) {
			return 0;
		}

		AmountLog al = new AmountLog();
		al.setCentreId(centreId);
		al.setOrderProductId(orderProductId);
		al.setOrderSn(orderSn);
		al.setMoney(BigDecimal.ZERO.subtract(money));
		if (StringUtils.isNotEmpty(orderSn)) {
			al.setRemark("结算站点自己供应商货款扣除商户余额,订单号：" + orderSn);
			if (orderProductId != null) {
				al.setRemark(al.getRemark().concat(",").concat(String.valueOf(orderProductId)));
			}
		}
		al.setFlowType(3);//站点自有供应商结算
		CentreAmount centreAmt = centreAmountMapper.getByKey(centreId);
		al.setBeforeamount(centreAmt.getAmount());
		al.setAfteramount(centreAmt.getAmount().subtract(money));

		//扣除商户余额
		int r = centreAmountMapper.deductAmount(centreId, money);
		if (r < 1) {
			throw new BDException(BusinessCode.CENTER_AMOUNT_NO_BALANCE);
		}
		amountLogMapper.saveAmountLog(al);
		return r;
	}

	@Override
	public int reduceAmount(CentreAmount centreAmount, String remark) {

		AmountLog al = new AmountLog();
		al.setCentreId(centreAmount.getCentreId());
		al.setMoney(BigDecimal.ZERO.subtract(centreAmount.getAmount()));
		// 获取request
		HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
		if (remark != null && !"".equals(remark)) {
			al.setRemark(remark.concat(",Ip:").concat(IPUtils.getIpAddr(request)).concat(",操作人:").concat(ShiroUtils.getUser().getNickname()));
		} else {
			al.setRemark("平台手动扣减商户余额".concat(",Ip:").concat(IPUtils.getIpAddr(request)).concat(",操作人:").concat(ShiroUtils.getUser().getNickname()));
		}
		al.setFlowType(6);//平台给站点扣款
		CentreAmount centreAmt = centreAmountMapper.getByKey(centreAmount.getCentreId());
		al.setBeforeamount(centreAmt.getAmount());
		al.setAfteramount(centreAmt.getAmount().subtract(centreAmount.getAmount()));

		int r = centreAmountMapper.deductAmount(centreAmount.getCentreId(), centreAmount.getAmount());
		if (r < 1) {
			throw new BDException(BusinessCode.CENTER_AMOUNT_NO_BALANCE);
		}
		amountLogMapper.saveAmountLog(al);
		return r;
	}
	/**
	 * 得到用户的商户
	 *
	 * @return
	 */
	@Override
	public Centre selectByMid(Long mid) {
		return centreMapper.selectByMid(mid);
	}


	/**
	 * 全部隐藏
	 *
	 * @param centreIds
	 * @return
	 */
	public int batchAllHiden(Integer hide) {
		return centreMapper.batchAllHiden(hide);
	}


	@Override
	public PageUtils<Centre> chooseCentreTable(String queryItem, int offset, int limit) {
		PageUtils<Centre> pageUtils = new PageUtils<>();
		Map<String, Object> map = new HashMap<>();
		if (StringUtils.isNotEmpty(queryItem)) {
			map.put("queryItem", queryItem);
		}
		int total = centreMapper.countByMap(map);
		if (total > 0) {
			logger.info("list centres, queryItem:{},total size:{}", queryItem, total);
			pageUtils.setTotal(total);
			pageUtils.setRows(centreMapper.selectByMap(map, new RowBounds(offset, limit)));
		} else {
			logger.info("list centres not found by: queryItem:{}", queryItem);
			pageUtils.setRows(new ArrayList<>());
		}
		return pageUtils;
	}

	@Override
	public Boolean checkExpriedDate(Long centreId) {
		Centre centre = centreMapper.selectByPrimaryKey(centreId);
		if (centre.getExpiredDate() == null) {
			return Boolean.FALSE;
		} else {
			if (centre.getExpiredDate().after(new Date())) {
				return Boolean.TRUE;
			} else {
				return Boolean.FALSE;
			}
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public int checkCentre(Long centreId) {

		//得到站点信息
		Centre centre = centreMapper.selectByPrimaryKey(centreId);
		centre.setStatus(CenterStatus.OPENED.getStatus());
		//判断是否审核通过
		if (StringUtils.isNotEmpty(centre.getStatus()) && centre.getStatus().trim().equals("1")) {
			if (centre.getPayStatus() != 2) {
				return 0;
			}
			//审核通过时间
			centre.setChecktime(new Date());
		}

		//直接通过后台创建的商户，需要新建
		if (centre.getMid() != null) {
			Member member = new Member();
			member.setId(centre.getMid());
			member.setIsCentre(1);
			//更新用户信息
			memberService.updateMember(member);
		}

		//创建后台管理系统的账号
		if (centre.getRenewMid() != null) {
			createAdminAccount(centre);
		}

		return centreMapper.updateByPrimaryKeySelective(centre);
	}


	public void createAdminAccount(Centre centre) {
		//用户电话号码
		String adminName = centre.getAccountMobile();
		//帐号存在逻辑删除
		if (userService.checkExit(adminName)) {
			userService.removeUser(centre.getMid(), "0");
		}
		//生成后台账号
		SysUser user = new SysUser();
		user.setName(adminName);
		user.setNickname(centre.getName());
		user.setPassword(SystemConstant.DEFAULT_PWD_USER.getConstants());
		user.setPhone(centre.getAccountMobile());
		/**商户账号创建新账号，默认为该商户账号**/
		user.setCentreId(centre.getCentreId());
		user.setFlag(PermisFlag.FLAG_CENTRE);
		String roleId = SystemConstant.USER_ID_MERCHANT_ADMIN.getConstants();
		//小程序申请的商户需要查询对应行业的角色id
		if(centre.getIndustryId() != null){
			CentreIndustry centreIndustry = centreIndustryMapper.selectByPrimaryKey(Long.valueOf(centre.getIndustryId()));
			if(centreIndustry != null && centreIndustry.getCentreRoleId() != null){
				roleId = centreIndustry.getCentreRoleId().toString();
			}
		}

		userService.saveUser(user, roleId);//商户超级管理员

		//查询门店，如果没有门店的话，就新建一个门店用户，同时创建后台管理系统账号
		List<Member> teamList = memberService.listCenterTeamList(centre.getCentreId());
		if (ValidateUtil.isEmptyCollection(teamList)) {//创建第一个门店
			Member member = new Member();
			member.setIsCentre(1);
			member.setIsHeadOffice(1);
			member.setCentreId(centre.getCentreId());
			member.setIsteam(MemberType.COMMANDER.getCode());
			member.setCheckTime(new Date());
			//数据库表非空字段
			member.setGender(1);
			member.setNickname(centre.getName());
			member.setMobile(centre.getAccountMobile());
			member.setsTime(new Date());
			member.setUpshopName(centre.getName());
			member.settProvince(centre.getProvince());
			member.settCity(centre.getCity());
			member.settArea(centre.getArea());
			member.settXiaoqu(centre.getName() + "总店");
			String coordinate = "";
			if (centre.getLon() != null) {
				coordinate = coordinate.concat(centre.getLon() + "").concat(",");
				member.setLng(centre.getLon().toString());
			}
			if (centre.getLat() != null) {
				coordinate = coordinate.concat(centre.getLat() + "");
				member.setLat(centre.getLat().toString());
			}
			member.settZuobiao(coordinate);
			//门店收银系统登录的账号
			member.setAdminUser(centre.getAccountMobile() + centre.getCentreId());
			//默认密码，123456
			member.setPwd(DigestUtils.sha256Hex(SystemConstant.DEFAULT_PWD_MEMBER.getConstants()));

			//更新用户站点标识
			memberMapper.insertSelective(member);

			member.setTeamid(member.getId());
			member.setUpshopTid(member.getId());
			memberMapper.updateByPrimaryKeySelective(member);

			//创建Store信息
			Store shopStore = new Store();
			shopStore.setLongitude(member.gettLng());
			shopStore.setLatitude(member.gettLat());
			shopStore.setMid(member.getId());
			shopStore.setStoreName(member.gettXiaoqu());
			shopStore.setTeamid(member.getId());
			shopStore.setStoreAddress(member.gettProvince() + member.gettCity() + member.gettArea() + member.gettAddress());
			storeMapper.insertSelective(shopStore);

			//创建门店的后台账号
			createShopAdminAccount(member, centre);
		}

	}

	@Override
	public Centre getPlatCenter() {
		return centreMapper.getPlatCenter();
	}

	public void createShopAdminAccount(Member shopUser, Centre centre) {
		Long centreId = centre.getCentreId();
		//用户电话号码
		String adminName = shopUser.getMobile() + centreId;
		//帐号存在逻辑删除
		if (userService.checkExit(adminName)) {
			userService.removeUser(shopUser.getId(), "0");
		}
		//生成后台账号
		SysUser user = new SysUser();
		user.setName(adminName);
		user.setNickname(shopUser.gettXiaoqu());
		user.setPassword(SystemConstant.DEFAULT_PWD_USER.getConstants());
		user.setPhone(shopUser.getMobile());
		/**商户账号创建新账号，默认为该商户账号**/
		user.setCentreId(centreId);
		user.setFlag(PermisFlag.FLAG_CENTRE);
		user.setTeamId(shopUser.getId());

		String roleId = getShopAdminId(centre);
		//小程序申请的门店需要查询对应行业的角色id
		if(centre.getIndustryId() != null){
			CentreIndustry centreIndustry = centreIndustryMapper.selectByPrimaryKey(Long.valueOf(centre.getIndustryId()));
			if(centreIndustry != null && centreIndustry.getStoreRoleId() != null){
				roleId = centreIndustry.getStoreRoleId().toString();
			}
		}

		userService.saveUser(user, roleId);//商户超级管理员

		try {
			//通知用户
			String msgContent = "您的门店【" + shopUser.gettXiaoqu() + "】后台管理帐号为：" + adminName + "，密码为：" + SystemConstant.DEFAULT_PWD_USER.getConstants() + "，欢迎您的加入！";
			// 发送短信
			try {
				//todo 短信通道暂无
//				shiYuanSmsClient.send(user.getPhone(), msgContent);
			} catch (Exception e) {
				e.printStackTrace();
			}
			Map<String, String> map = new HashMap<>();
			map.put("url", templatemsgCreateUserUrl);
			map.put("accounts", adminName);
			map.put("accountsStr", "用户名："+adminName);
			map.put("pwdStr", "您的密码为"+SystemConstant.DEFAULT_PWD_USER.getConstants());
			map.put("pwd", SystemConstant.DEFAULT_PWD_USER.getConstants());
			map.put("type", "门店【" + shopUser.gettXiaoqu() + "】后台管理帐号创建");
			map.put("createdDate", DateUtil.convertDateToStr(new Date(), DateUtil.yyyy_MM_dd_HH_mm_ss));
			map.put("type0", "门店【" + shopUser.gettXiaoqu() + "】后台管理帐号创建成功");
			String str = "";
			str += "用户名: " + adminName + ",\n";
			str += "用户密码: " + SystemConstant.DEFAULT_PWD_USER.getConstants() + ",\n";
			map.put("remark", str);
			map.put("status", "创建成功,已启用!");
			//发送模版消息
			orderService.sendAccountsTemplateToUser(centreId, shopUser.getId(), map);
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
		}
	}

	public String getShopAdminId(Centre centre) {
		String shopAdminId = SystemConstant.USER_ID_SHOP_ADMIN.getConstants();
		return shopAdminId;
	}

	public PageUtils<Centre> listCentresByAgent(SysUser user, String name, String type, String status, int offset, int limit) {
		PageUtils<Centre> pageUtils = new PageUtils<>();

		CentreExample centreExample = new CentreExample();
		CentreExample.Criteria criteria = centreExample.createCriteria();
		Map<String, Object> map = new HashMap<>();
		if (StringUtils.isNotEmpty(name)) {
			criteria.andNameLike('%' + name + '%');
			map.put("name", name);
		}

		if (StringUtils.isNotEmpty(type)) {
			criteria.andTypeEqualTo(type);
			map.put("type", type);
		}
		if (StringUtils.isNotEmpty(status)) {
			criteria.andStatusEqualTo(status);
			map.put("status", status);
		}
		//如果是分公司或者代理，则只显示自己旗下得商户
		if (user.getFlag().equals(PermisFlag.BranchOffice)
				|| user.getFlag().equals(PermisFlag.AgentLevel1)
				|| user.getFlag().equals(PermisFlag.AgentLevel2)
				|| user.getFlag().equals(PermisFlag.AgentLevel3)) {
			map.put("loginUserId", user.getUserId());
			{
				logger.info("list centres not found by: name:{}, type:{}, status:{}", name, type, status);
				pageUtils.setRows(new ArrayList<>());
			}
		} else {
			int total = centreMapper.countByExample(centreExample);
			if (total > 0) {
				logger.info("list centres, name:{}, type:{}, status:{},total size:{}", name, type, status, total);
				pageUtils.setTotal(total);
				centreExample.setOrderByClause("create_time desc");
				pageUtils.setRows(centreMapper.selectByExample(centreExample, new RowBounds(offset, limit)));
			} else {
				logger.info("list centres not found by: name:{}, type:{}, status:{}", name, type, status);
				pageUtils.setRows(new ArrayList<>());
			}
		}
		return pageUtils;
	}
}
